package com.aizuda.boot.modules.third.wps.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aizuda.boot.modules.file.domain.entity.FileInfo;
import com.aizuda.boot.modules.file.mapper.FileInfoMapper;
import com.aizuda.boot.modules.third.wps.domain.entity.FileHistory;
import com.aizuda.boot.modules.third.wps.enums.WebOfficeErrEnum;
import com.aizuda.boot.modules.third.wps.exception.WebOfficeException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aizuda.boot.modules.third.wps.mapper.FileHistoryMapper;
import org.springframework.transaction.annotation.Transactional;

@Service
public class FileHistoryService extends ServiceImpl<FileHistoryMapper, FileHistory> {

    private String uploadPath;

    @Value("${file.storage.local.upload-path:#{null}}")
    public void setUploadPath(String uploadPath) {
        this.uploadPath = StrUtil.isBlank(uploadPath) ? System.getProperty("java.io.tmpdir") + File.separator : uploadPath;
    }

    @Value("${file.storage.local.url-prefix}")
    private String urlPrefix;

    @Autowired
    private FileInfoMapper fileInfoMapper;

    /**
     * 上传历史文件
     *
     * @param fileId  文件 ID
     * @param content 上传的文件
     * @param userId  用户 ID
     * @return String filekey
     */
    @Transactional(rollbackFor = Exception.class)
    public String uploadNewVersion(String fileId, byte[] content, String userId) {
        // 根据文件id查询文件信息 如果不存在则抛出异常
        FileInfo fileInfo = fileInfoMapper.selectById(fileId);
        if (fileInfo == null) {
            throw new WebOfficeException(WebOfficeErrEnum.FILE_NOT_FOUND, "文件不存在");
        }

        // 查询最新的历史记录
        FileHistory latestHistory = this.lambdaQuery()
                .eq(FileHistory::getFileId, fileId)
                .orderByDesc(FileHistory::getVersion)
                .last("LIMIT 1")
                .one();

        //使用时间戳生成新版本
        String newVersion = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");

        String fileKey = fileInfo.getFileKey();
        String sourceFilePath = StrUtil.subBefore(fileKey, ".", true);
        String filePath = uploadPath + sourceFilePath + File.separator;
        File directory = new File(filePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        //获取不带后缀的文件名
        String originalFileName = fileInfo.getFileName();
        String fileType = fileInfo.getFileType();
        String newFileName = "V" + newVersion + "." + fileType;
        fileKey = sourceFilePath + File.separator + newFileName;
        File fileTemp = new File(new File(filePath + newFileName).getAbsolutePath());
        try {
            Files.write(fileTemp.toPath(), content);
        } catch (IOException e) {
            if (fileTemp.exists() && fileTemp.isFile()) {
                fileTemp.delete();
            }
            log.error("", e);
            throw new WebOfficeException(WebOfficeErrEnum.FILE_NOT_UPLOADED);
        }

        // 保存历史记录(版本号等完成通知更新)
        this.save(FileHistory.builder()
                .fileId(Long.valueOf(fileId))
                .fileKey(fileKey)
                .fileName(fileInfo.getFileName())
                .fileSize(Long.valueOf(content.length))
                .creatorId(userId)
                .modifierId(userId)
                .build());

        return fileKey;

    }
}
